# 定义路径变量
USERHOME := /home/weilaidb
LINUX_KERNEL_PATH := $(USERHOME)/kernel/linux.old1
MODULE_PATH := $(USERHOME)/kernel/selfqemu/modules
BUSYBOX_PATH := $(USERHOME)/kernel/selfqemu/rootfs/busybox-1.36.1
BUSYBOX_INSTALL_PATH := $(USERHOME)/kernel/selfqemu/rootfs/busybox-1.36.1/_install
ROOTFS_PATH := $(USERHOME)/kernel/selfqemu/rootfs
QEMU_CMD := qemu-system-x86_64 \
    -kernel $(LINUX_KERNEL_PATH)/arch/x86/boot/bzImage \
    -append "root=/dev/ram rdinit=/sbin/init console=ttyS0" \
    -initrd $(ROOTFS_PATH)/rootfs.cpio.gz \
    -nographic \
    -serial mon:stdio \
	# -enable-kvm  # 如果支持KVM加速


QEMU_CMD_GDB := qemu-system-x86_64 \
    -kernel $(LINUX_KERNEL_PATH)/arch/x86/boot/bzImage \
    -append "root=/dev/ram rdinit=/sbin/init console=ttyS0 nokaslr" \
    -initrd $(ROOTFS_PATH)/rootfs.cpio.gz \
    -nographic \
    -serial mon:stdio \
	 -s -S  # -s: 启动 GDB 服务器（默认端口 1234）, -S: 启动时暂停 CPU
	# -enable-kvm  # 如果支持KVM加速




.PHONY: all help busybox pack_rootfs compile_module run_qemu run_qemu_gdb

# 帮助信息
help:
	@echo "======= Help List ======"
	@echo "all: 执行所有目标（打包 busybox、编译模块、打包根文件系统、启动 QEMU）"
	@echo "allgdb: 执行所有目标（打包 busybox、编译模块、打包根文件系统、启动 QEMUGDB）"
	@echo "busybox: 打包 busybox"
	@echo "compile_module: 编译模块"
	@echo "pack_rootfs: 打包根文件系统"
	@echo "run_qemu: 启动 QEMU"
	@echo "run_qemu_gdb: 启动 QEMU(GDB)"

# 默认目标
# all: busybox compile_module pack_rootfs run_qemu
all: compile_module pack_rootfs run_qemu

# allgdb: busybox compile_module pack_rootfs run_qemu_gdb
allgdb: compile_module pack_rootfs run_qemu_gdb

# 打包 busybox
# 先不要编译，选择build static library
busybox:
	@echo "打包 busybox..."
	@make -C $(BUSYBOX_PATH) clean
	@make -C $(BUSYBOX_PATH) defconfig
	#make menuconfig 选择build static library
	@make -C $(BUSYBOX_PATH) install
	@echo "busybox 打包完成"

# 编译模块
# 编译模块
compile_module:
	@echo "编译模块...";\
	set -e; \
	make -C $(MODULE_PATH)/my_first_module; \
	make -C $(MODULE_PATH)/my_char_driver ; \
	echo "模块编译完成"

# 打包根文件系统(放在_install路径下查找，打的最小）
pack_rootfs:
	@echo "打包根文件系统..."
	@cd $(BUSYBOX_INSTALL_PATH) && find . | cpio -o -H newc | gzip > ../../rootfs.cpio.gz
	@echo "根文件系统打包完成"

# 启动 qemu
run_qemu:
	@echo "启动 QEMU..."
	@$(QEMU_CMD)
	
# 启动 qemu
run_qemu_gdb:
	@echo "启动 QEMU(GDB)..."
	@$(QEMU_CMD_GDB)
	





# 错误处理
# .DEFAULT_GOAL := help
.SHELLFLAGS := -e -c

# # 找到并修改此行（仅用于调试）
# KBUILD_CFLAGS   := -O0 -Wall -Wundef -Wstrict-prototypes